// 项目配置管理器
class ConfigManager {
    constructor() {
        this.config = null;
        this.loaded = false;
    }

    // 加载配置文件
    async loadConfig() {
        try {
            // 优先从后端 API 获取配置
            const apiResponse = await fetch('/api/config');
            
            if (apiResponse.ok) {
                const result = await apiResponse.json();
                if (result.success && result.data) {
                    this.config = result.data;
                    this.loaded = true;
                    return this.config;
                }
            }
            
            throw new Error('后端 API 获取配置失败');
        } catch (apiError) {
            console.error('❌ 后端 API 获取配置失败:', apiError.message);
            // 不再有降级方案，抛出错误
            throw new Error('无法从后端API获取配置，请启动后端服务器');
        }
    }


    // 获取配置值（支持点号路径）
    get(path, defaultValue = null) {
        if (!this.loaded) {
            console.warn('⚠️ 配置未加载，返回默认值');
            return defaultValue;
        }

        const keys = path.split('.');
        let value = this.config;

        for (const key of keys) {
            if (value && typeof value === 'object' && key in value) {
                value = value[key];
            } else {
                return defaultValue;
            }
        }

        return value;
    }

    // 设置配置值（支持点号路径）
    set(path, value) {
        if (!this.loaded) {
            console.warn('⚠️ 配置未加载，无法设置值');
            return false;
        }

        const keys = path.split('.');
        let target = this.config;

        for (let i = 0; i < keys.length - 1; i++) {
            const key = keys[i];
            if (!target[key] || typeof target[key] !== 'object') {
                target[key] = {};
            }
            target = target[key];
        }

        target[keys[keys.length - 1]] = value;
        return true;
    }

    // 检查是否启用认证
    isAuthEnabled() {
        return this.get('auth.enabled', true);
    }

    // 获取相机配置
    getCameraConfig() {
        return this.get('camera', {});
    }

    // 获取UI配置
    getUIConfig() {
        return this.get('ui', {});
    }

    // 获取编辑器配置
    getEditorConfig() {
        return this.get('editor', {});
    }

    // 获取性能配置
    getPerformanceConfig() {
        return this.get('performance', {});
    }

    // 获取调试配置
    getDebugConfig() {
        return this.get('debug', {});
    }

    // 获取认证配置
    getAuthConfig() {
        return this.get('auth', {});
    }

    // 应用配置到页面
    applyConfig() {
        if (!this.loaded) return;

        // 应用UI配置
        const uiConfig = this.getUIConfig();
        this.applyUIConfig(uiConfig);

        // 应用调试配置
        const debugConfig = this.getDebugConfig();
        this.applyDebugConfig(debugConfig);
    }

    // 应用UI配置
    applyUIConfig(uiConfig) {
        // 应用主题
        if (uiConfig.theme) {
            document.body.setAttribute('data-theme', uiConfig.theme);
        }

        // 应用面板透明度
        if (uiConfig.panelOpacity !== undefined) {
            const controls = document.getElementById('controls');
            if (controls) {
                controls.style.opacity = uiConfig.panelOpacity;
            }
        }

        // 显示/隐藏用户信息
        if (uiConfig.showUserInfo === false) {
            const userInfo = document.querySelector('.user-info');
            if (userInfo) {
                userInfo.style.display = 'none';
            }
        }

        // 显示/隐藏相机提示
        if (uiConfig.showCameraTips === false) {
            const cameraTips = document.getElementById('camera-tips');
            if (cameraTips) {
                cameraTips.style.display = 'none';
            }
        }

        // 显示/隐藏场景信息
        if (uiConfig.showSceneInfo === false) {
            const sceneInfo = document.getElementById('info');
            if (sceneInfo) {
                sceneInfo.style.display = 'none';
            }
        }
    }

    // 应用调试配置
    applyDebugConfig(debugConfig) {
        if (debugConfig.enabled) {
            // 启用调试模式
            window.DEBUG = true;
            
            // 显示FPS
            if (debugConfig.showFPS) {
                this.enableFPSDisplay();
            }

            // 显示内存使用
            if (debugConfig.showMemory) {
                this.enableMemoryDisplay();
            }
        }
    }

    // 启用FPS显示
    enableFPSDisplay() {
        const fpsDiv = document.createElement('div');
        fpsDiv.id = 'fps-display';
        fpsDiv.style.cssText = `
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            z-index: 10000;
        `;
        document.body.appendChild(fpsDiv);

        let lastTime = performance.now();
        let frameCount = 0;

        function updateFPS() {
            frameCount++;
            const currentTime = performance.now();
            
            if (currentTime - lastTime >= 1000) {
                const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
                fpsDiv.textContent = `FPS: ${fps}`;
                frameCount = 0;
                lastTime = currentTime;
            }
            
            requestAnimationFrame(updateFPS);
        }
        
        updateFPS();
    }

    // 启用内存显示
    enableMemoryDisplay() {
        if (!performance.memory) {
            console.warn('⚠️ 浏览器不支持内存监控');
            return;
        }

        const memoryDiv = document.createElement('div');
        memoryDiv.id = 'memory-display';
        memoryDiv.style.cssText = `
            position: fixed;
            top: 40px;
            right: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            z-index: 10000;
        `;
        document.body.appendChild(memoryDiv);

        function updateMemory() {
            const memory = performance.memory;
            const used = Math.round(memory.usedJSHeapSize / 1024 / 1024);
            const total = Math.round(memory.totalJSHeapSize / 1024 / 1024);
            memoryDiv.textContent = `Memory: ${used}MB / ${total}MB`;
            
            setTimeout(updateMemory, 1000);
        }
        
        updateMemory();
    }

    // 获取完整配置
    getAll() {
        return this.config;
    }

    // 重新加载配置
    async reload() {
        this.loaded = false;
        return await this.loadConfig();
    }
}

// 创建全局配置管理器实例
window.configManager = new ConfigManager();

// 导出配置管理器
export { ConfigManager };
export default window.configManager;
